package com.jgsu.farm.service.impl;

import com.jgsu.farm.entity.Plant;
import com.jgsu.farm.entity.Rule;
import com.jgsu.farm.entity.StressCategory;
import com.jgsu.farm.entity.User;
import com.jgsu.farm.exception.DataAddException;
import com.jgsu.farm.exception.DataNotExistException;
import com.jgsu.farm.mapper.PlantMapper;
import com.jgsu.farm.mapper.RuleMapper;
import com.jgsu.farm.mapper.StressCategoryMapper;
import com.jgsu.farm.mapper.UserMapper;
import com.jgsu.farm.mapper.sql.RuleMapperSql;
import com.jgsu.farm.mapper.sql.UserMapperSql;
import com.jgsu.farm.service.RuleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RuleServiceImpl implements RuleService {
   @Autowired
    RuleMapper ruleMapper;
   @Autowired
   UserMapper userMapper;
   @Autowired
   PlantMapper plantMapper;
   @Autowired
   StressCategoryMapper stressCategoryMapper;


    @Override
    public void add(Rule rule) {
        User user = userMapper.selectByPrimaryKey(rule.getAuthor());
        Plant plant = plantMapper.selectByPrimaryKey(rule.getCropid());
        StressCategory stressCategory = stressCategoryMapper.selectByPrimaryKey(rule.getStresstype());
        if(user == null || plant == null || stressCategory == null){
            throw new DataAddException("604","用户id或植物id或植物分类id不存在");
        }else {
            ruleMapper.insert(rule);
        }
    }

    @Override
    public void delete(Integer ruleid) {
        Integer ruleId = ruleMapper.deleteByPrimaryKey(ruleid);
        if (ruleId == 0 || ruleId == null) {
            throw new DataNotExistException("603", "不存在该id,诊断规则删除失败");
        }
    }

    @Override
    public PageInfo<Rule> selectAll(int page, int pagesize) {
        PageHelper.startPage(page, pagesize);
        List<Rule> rules = ruleMapper.selectAll();
        PageInfo<Rule> pageInfoRuleList = new PageInfo<>(rules);
        return pageInfoRuleList;
    }


    @Override
    public void update(Rule rule) {
        Rule ruleId = ruleMapper.selectByPrimaryKey(rule.getRuleid());
        User user = userMapper.selectByPrimaryKey(rule.getAuthor());
        Plant plant = plantMapper.selectByPrimaryKey(rule.getCropid());
        StressCategory stressCategory = stressCategoryMapper.selectByPrimaryKey(rule.getStresstype());
        if (ruleId == null || user == null || plant == null || stressCategory == null) {
            throw new DataNotExistException("604", "数据更新失败，规则id或用户id或植物id或植物分类id不存在");
        } else {
            ruleMapper.updateByPrimaryKey(rule);
        }
    }
}
